package com.example.agvctrl;

        import android.content.BroadcastReceiver;
        import android.content.ComponentName;
        import android.content.Context;
        import android.content.Intent;
        import android.content.IntentFilter;
        import android.content.ServiceConnection;
        import android.graphics.Bitmap;
        import android.graphics.BitmapFactory;
        import android.media.Ringtone;
        import android.media.RingtoneManager;
        import android.net.Uri;
        import android.os.Bundle;

        import com.google.android.material.floatingactionbutton.FloatingActionButton;
        import com.google.android.material.snackbar.Snackbar;

        import androidx.annotation.NonNull;
        import androidx.appcompat.app.AppCompatActivity;
        import androidx.appcompat.widget.Toolbar;

        import android.os.Handler;
        import android.os.IBinder;
        import android.os.Message;
        import android.util.Log;
        import android.view.View;
        import android.widget.EditText;
        import android.widget.ImageView;
        import android.widget.TextView;
        import android.widget.Toast;




        import org.json.JSONObject;

        import java.io.ByteArrayOutputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.net.MalformedURLException;
        import java.net.URI;
        import java.net.URL;
        import java.net.URLConnection;

public class AgvCtrl extends AppCompatActivity {

    private String urlString = "http://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";
    //"http://192.168.31.3/1.html";
    String ip = "10.42.0.1";
    String ip2 = "119.3.183.213";
    String IP = "0.0.0.0";
    private ImageView mIV;
    private int fileLength;
    private Bitmap mBitmap;
    private TextView mBattery;
    private TextView mAgv;
    private TextView mArm;
    private TextView mLink;
    int battery = 94;
    int distant = -1;
    String agvStatus = "0";
    String armStatus = "0";
    String linkStatus = "0";

    private JWebSocketClient client;
    private JWebSocketClientService.JWebSocketClientBinder binder;
    private JWebSocketClientService jWebSClientService;
    BeepReceive beepReceive;
    private Ringtone r;

    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("AgvCtlr", "服务与活动成功绑定");
            binder = (JWebSocketClientService.JWebSocketClientBinder) service;
            jWebSClientService = binder.getService();
            client = jWebSClientService.client;

            URI uri = URI.create("ws://" + IP + ":5000/makeSocket/test2");
            jWebSClientService.initConnect(uri);
            //jWebSClientService.connect();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("AgvCtlr", "服务与活动成功断开");
            jWebSClientService = null;
        }
    };

    class BeepReceive extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            String msgType = intent.getStringExtra("type");
            if( msgType !=null)
            if (msgType.equals("msg") )
            {
                String message = intent.getStringExtra("message");
                Toast.makeText(getApplicationContext(), "警告："+message, Toast.LENGTH_SHORT).show();
                beep();
            }
            else if (msgType.equals("initOK"))
            {
                linkStatus = "1";
            }
            else if(msgType.equals("close"))
            {
                linkStatus = "0";
            }

            updateActive.sendEmptyMessage(0);
        }
    }

    private void beep() {
        r.play();
    }

    private void bindService() {
        Intent bindIntent = new Intent(AgvCtrl.this, JWebSocketClientService.class);
        bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE);
    }
    public void registerReceiver(){
        beepReceive = new BeepReceive();
        IntentFilter intentFilter = new IntentFilter("com.example.agvctrl.beep");
        registerReceiver(beepReceive,intentFilter);
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_agv_ctrl);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mBattery = (TextView) findViewById(R.id.battery);
        mAgv = (TextView) findViewById(R.id.agvStatus);
        mArm = (TextView) findViewById(R.id.armStatus);
        mLink = (TextView) findViewById(R.id.linkStatus);
        mIV = (ImageView) findViewById(R.id.image);
        IP = ip2;

        bindService();
        registerReceiver();
        Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        r = RingtoneManager.getRingtone(getApplicationContext(), notification);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(serviceConnection);
        unregisterReceiver(beepReceive);
    }

    public byte[] readStream(InputStream in) throws Exception {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = in.read(data)) != -1) {
            total += count;
//            mSeekBar.setProgress((int)(total*100)/fileLength);
            bos.write(data, 0, count);
        }
        bos.close();
        in.close();
        return bos.toByteArray();
    }

    private Runnable downloadRunn = new Runnable() {
        @Override
        public void run() {
            try {
                String filePath = "a.png";
                URL url = new URL(urlString);
                URLConnection con = url.openConnection();
                con.connect();
                int lengthen = con.getContentLength();
                InputStream in = con.getInputStream();
                byte[] arr = readStream(in);
                mBitmap = BitmapFactory.decodeByteArray(arr, 0, lengthen);
                //save
                updateActive.sendEmptyMessage(0);
            } catch (MalformedURLException e) {
                e.printStackTrace();
                //Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
            } catch (IOException e) {
                e.printStackTrace();
                //Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    };
    private Runnable updateRunn = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(urlString);
                URLConnection con = url.openConnection();
                con.connect();
                int lengthen = con.getContentLength();
                InputStream in = con.getInputStream();
                byte[] arr = readStream(in);
                JSONObject answers = new JSONObject(new String(arr));
                String data = answers.getString("data");
                JSONObject answer = new JSONObject(data);
                battery = answer.getInt("battery");
                agvStatus = answer.getString("status");
                distant = answer.getInt("measure");
                updateActive.sendEmptyMessage(0);
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    private Handler updateActive = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //Toast.makeText(getApplicationContext(), "urlOk", Toast.LENGTH_SHORT).show();
            if (mBitmap != null)
                mIV.setImageBitmap(mBitmap);
            mAgv.setText("AGV装置状态：" + agvStatus);
            mBattery.setText("设备电量：" + Integer.toString(battery));
            mLink.setText("设备状态:"+linkStatus);
        }
    };

    public void measure(View view) {
        //playBtn
        String inputText = ((EditText) findViewById(R.id.editView)).getText().toString();
        urlString = "http://" + IP + ":5000/agv/measure";
        new Thread(updateRunn).start();
    }

    public void agvSet(View view) {
        //playBtn
        String inputText = ((EditText) findViewById(R.id.editView)).getText().toString();
        String cmd = "0";
        switch (view.getId()) {
            case R.id.goStop:
                cmd = "0";
                break;
            case R.id.goFront:
                cmd = "1";
                break;
            case R.id.goBack:
                cmd = "2";
                break;
            case R.id.goLeft:
                cmd = "3";
                break;
            case R.id.goRight:
                cmd = "4";
                break;
        }
        urlString = "http://" + IP + ":5000/agv/ctrl?cmd=" + cmd + "&arg=0";
        new Thread(downloadRunn).start();
    }

    public void cameraShot(View view) {
        //playBtn
        urlString = "http://" + IP + ":5000/cameraShot";
        new Thread(downloadRunn).start();
    }

//    public void testc(View view) {
//        Intent intentTest = new Intent(this, control.class);
//        startActivity(intentTest);
//    }

    public void changeIP(View view) {
        if (IP == ip)
            IP = ip2;
        else
            IP = ip;
        Toast.makeText(getApplicationContext(), IP, Toast.LENGTH_SHORT).show();
        unbindService(serviceConnection);
        bindService();
    }
    public void armCtrl(View view){
        Intent intentTest = new Intent(this,ArmCtrl.class);
        Bundle bundle = new Bundle();
        bundle.putString("ip",IP);
        intentTest.putExtras(bundle);
        startActivity(intentTest);
    }
}

